package com.tanhua.gateway.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网关统一鉴权：看用户是否登录了。判断是否存在token
 * netflix: 网关zuul order 与springcloud gateway是一样的效果
 */
@Component
@Slf4j
//Ordered作用，定义顺序 spring框架通用
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${gateway.excludedUrls}")
    private List<String> excludedUrls;

    /**
     * 鉴权逻辑
     * @param exchange 交换机: 获取request, response
     * @param chain 过滤链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 过虑那些白名单, 发送验证码，登录校验
        // 1.1 获取请求的url地址
        // uri包含http://ip:port/.....
        // getPath
        String requestPath = request.getURI().getPath();
        String method = request.getMethod().name();
        log.info(method + " 方式请求了地址: " + requestPath);
        if (excludedUrls.contains(requestPath)) {
            return chain.filter(exchange);
        }
        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3. 获取请求头Authorization
        String token = request.getHeaders().getFirst("Authorization");
        //4. 有值
        if(StringUtils.isNotEmpty(token)) {
            // 后台管理系统请求过来时，带上的
            token = token.replace("Bearer ","");
            //5. 拼接redis中的key
            String tokenKey = "TOKEN_" + token;
            //6. 获取redis中的值
            String loginUserJson = stringRedisTemplate.opsForValue().get(tokenKey);
            //7. 有值 放行
            if(StringUtils.isNotEmpty(loginUserJson)){
                return chain.filter(exchange);
            }
        }
        log.error("***********用户未登录**********");
        //8. 没值 401， 用户没有登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("errCode", 401);
        responseData.put("errMessage", "用户未登录");
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(responseData));
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 返回过滤链中执行的顺序
     * 值越小越优先执行
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}